package com.tro.mail.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.tro.common.util.string.AESTool;
import com.tro.mail.dao.entity.MailMain;

public class SendEmail {
	
	public SendEmail(){
		
	}
	
	/**
	 * @return
	 * attachments  附件集合
	 * recipients   收件人集合
	 * UserId       发送人USERID
	 * */
	public boolean sendInter(String email,String password,List<File> attachments,List<String> recipients,MailMain m) throws UnsupportedEncodingException, MessagingException{
		boolean falg=false;
		AESTool aes = new AESTool();
			//邮件发送
			try {
				String subject="";//邮件主题
				String path = Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(0)+"sysconf.properties";
				//第二步，添加发送协议
				Properties props = null;
				props = System.getProperties();
				//根据发送邮箱的账号解析出smtp服务器  
				String smtpHostName = "smtp." + email.split("@")[1];  
                //初始化props  
				props.put("mail.smtp.ssl.enable", "true");  
				props.put("mail.smtp.host", smtpHostName);
				Session session = null;
				MimeMessage mimeMsg = null;
				Multipart mp = null;
				try {
					session = Session.getDefaultInstance(props, null);//发送email首先要获取session对象
					mimeMsg = new MimeMessage(session);
					mp = new MimeMultipart();
				} catch (Exception e) {
					e.printStackTrace(); 
				}
				props.put("mail.smtp.auth", "true");
				// 第三步，添加邮件主题
				mimeMsg.setSubject(MimeUtility.encodeText(subject,MimeUtility.mimeCharset("utf-8"), m.getMailTitle()));		
				//第四步，添加邮件正文
				BodyPart bp = new MimeBodyPart();
				bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=UTF-8>"+m.getMailContent(), "text/html;charset=UTF-8");
				mp.addBodyPart(bp);
				mimeMsg.setFrom(new InternetAddress(email));
				
				// 第五步，添加收件人，邮件群发
				InternetAddress[] addresses =  new InternetAddress[recipients.size()];  
				for(int i=0; i< addresses.length; i++) {  
					addresses[i] = new InternetAddress();  
				}  
				mimeMsg.setRecipients(Message.RecipientType.TO, addresses);//收件人
				
				//附件单发
				/*if(!StringUtils.isBlank("")){
					File usFile = new File("");  
					MimeBodyPart fileBody = new MimeBodyPart();  
					DataSource source = new FileDataSource("");  
					fileBody.setDataHandler(new DataHandler(source));  
					sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();  
					fileBody.setFileName("=?GBK?B?"+ enc.encode(usFile.getName().getBytes()) + "?=");  
					mp.addBodyPart(fileBody);  
					mimeMsg.setContent(mp);
					mimeMsg.saveChanges();
				}else{
					mimeMsg.setContent(mp);
					mimeMsg.saveChanges();
				}*/
				
				//附件群发
				if(attachments != null) {  
					for(File attachment : attachments) {  
						BodyPart attachmentPart = new MimeBodyPart();  
						DataSource source = new FileDataSource(attachment);  
						attachmentPart.setDataHandler(new DataHandler(source));  
						//避免中文乱码的处理  
						attachmentPart.setFileName(MimeUtility.encodeWord(attachment.getName()));  
						mp.addBodyPart(attachmentPart);  
					}  
				}
				mimeMsg.setContent(mp);  
				//保存邮件  
				mimeMsg.saveChanges();  
				//发送邮件
				Transport transport = session.getTransport("smtp");
				transport.connect((String) props.get("mail.smtp.host"), email,password);
				//transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));//添加抄送人
				transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));//发送
				transport.close();
				falg=true;
			} catch (Exception e) {
				e.printStackTrace();
				falg=false;
			}	
		return falg;
	}
	
	
	/**
	 * 单发
	 * */
	public boolean sendInter(String email,String password, List<Map<String, Object>> attachments,String recipients,MailMain m) throws UnsupportedEncodingException, MessagingException{
		boolean falg=false;
		AESTool aes = new AESTool();
			//邮件发送
			try {
				String subject="";//邮件主题
				String path = Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(0)+"sysconf.properties";
				//第二步，添加发送协议
				Properties props = null;
				props = System.getProperties();
                //根据发送邮箱的账号解析出smtp服务器  
				String smtpHostName = "smtp." + email.split("@")[1];  
                //初始化props  
				props.put("mail.smtp.ssl.enable", "true");  
				props.put("mail.smtp.host", smtpHostName);  

				Session session = null;
				MimeMessage mimeMsg = null;
				Multipart mp = null;
				try {
					session = Session.getDefaultInstance(props, null);//发送email首先要获取session对象
					mimeMsg = new MimeMessage(session);
					mp = new MimeMultipart();
				} catch (Exception e) {
					e.printStackTrace(); 
				}
				props.put("mail.smtp.auth", "true");
				// 第三步，添加邮件主题
				mimeMsg.setSubject(MimeUtility.encodeText(subject,MimeUtility.mimeCharset("utf-8"), m.getMailTitle()));		
				//第四步，添加邮件正文
				BodyPart bp = new MimeBodyPart();
				bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=UTF-8>"+m.getMailContent(), "text/html;charset=UTF-8");
				mp.addBodyPart(bp);
				mimeMsg.setFrom(new InternetAddress(email));
				
				// 第五步，添加收件人，邮件群发
				mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));//收件人
				
				//附件单发
				/*if(!StringUtils.isBlank("")){
					File usFile = new File("");  
					MimeBodyPart fileBody = new MimeBodyPart();  
					DataSource source = new FileDataSource("");  
					fileBody.setDataHandler(new DataHandler(source));  
					sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();  
					fileBody.setFileName("=?GBK?B?"+ enc.encode(usFile.getName().getBytes()) + "?=");  
					mp.addBodyPart(fileBody);  
					mimeMsg.setContent(mp);
					mimeMsg.saveChanges();
				}else{
					mimeMsg.setContent(mp);
					mimeMsg.saveChanges();
				}*/
				
				//附件群发
				if(attachments != null) {  
					for(Map<String, Object> attachment : attachments) {  
						File file=(File)attachment.get("file");
						String fileName=attachment.get("fileName").toString();
						BodyPart attachmentPart = new MimeBodyPart();  
						DataSource source = new FileDataSource(file);  
						attachmentPart.setDataHandler(new DataHandler(source));  
						//避免中文乱码的处理  
						attachmentPart.setFileName(MimeUtility.encodeWord(fileName));  
						mp.addBodyPart(attachmentPart);  
					}  
				}
				mimeMsg.setContent(mp);  
				//保存邮件  
				mimeMsg.saveChanges();  
				//发送邮件
				Transport transport = session.getTransport("smtp");
				transport.connect((String) props.get("mail.smtp.host"), email,password);
				//transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));//添加抄送人
				transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));//发送
				transport.close();
				falg=true;
			} catch (Exception e) {
				e.printStackTrace();
				falg=false;
			}	
		return falg;
	}
	
}
